package com.ly.game;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class GameServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private GameDao gameDao = new GameDao();

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		String command = request.getParameter("command");
		if ("list".equals(command)) {
			list(request, response);
		} else if ("delete".equals(command)) {
			delete(request, response);
		} else if ("preUpdate".equals(command)) {
			preUpdate(request, response);
		} else if ("preUpdate".equals(command)) {
			preUpdate(request, response);
		} else if ("update".equals(command)) {
			update(request, response);
		}
	}

	private void list(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		List<GameEntity> GameList = gameDao.list();
		request.setAttribute("GameList", GameList);
		request.getRequestDispatcher("view/game-list.jsp").forward(request,
				response);
	}

	private void delete(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		int id = Integer.parseInt(request.getParameter("id"));
		gameDao.delete(id);
		response.sendRedirect("GameServlet?command=list");
	}

	private void preUpdate(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		int id = Integer.parseInt(request.getParameter("id"));
		GameEntity game = gameDao.preUpdate(id);
		request.setAttribute("game", game);
		request.getRequestDispatcher("view/game-update.jsp").forward(request,
				response);
	}
	private void update(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		int id = Integer.parseInt(request.getParameter("id"));
		String code=request.getParameter("code");
		String name=request.getParameter("code");
		int grade = Integer.parseInt(request.getParameter("grade"));
		int money = Integer.parseInt(request.getParameter("money"));
		String mome=request.getParameter("mome");
		
		GameEntity game =new GameEntity();
		game.setId(id);
		game.setCode(code);
		game.setName(name);
		game.setGrade(grade);
		game.setMoney(money);
		game.setMome(mome);
		
		gameDao.update(game);
		response.sendRedirect("GameServlet?command=list");
	}
}
